package service;

import java.util.List;

import model.EventFieldConditionDetail;
import model.EventFieldsCondition;
import model.Field;
import model.FieldsType;
import model.UserEvent;
import model.UserEventDetail;

import org.apache.commons.lang.StringUtils;

import dao.EventFieldsConditionDao;
import dao.FieldDao;

public class MonitorServiceImpl implements MonitorService {
	FieldDao fDao;
	EventFieldsConditionDao efcDao;
	
	@Override
	public String generateQueryStringByUserEvent(UserEventDetail ued) {
		//1.根据userEvent的tId获得type为TimeStamp的字段
		UserEvent userEvent = ued.getUserEvent();
		fDao = new FieldDao();
		Field fieldTimeStamp  = fDao.getFieldNameByTidAndType(userEvent.gettId(), FieldsType.TIMESTAMP.value());
		String timeStampPart="";
		if (!StringUtils.isBlank(fieldTimeStamp.getFieldName())){
			timeStampPart = fieldTimeStamp.getFieldName()+" between dateadd(ms,-"+userEvent.getTimeSpan()+",getDate()) and  getDate()";
		}
		
		//2.根据userEvent的ueId获得其监控字段与location字段的列表
		efcDao = new EventFieldsConditionDao();
		List<EventFieldConditionDetail> efcdList = efcDao.getEventFieldConditionDetailsByUeId(userEvent.getuId());
		
		String fieldsPart = "";
		String conditionPart = "";
		if(efcdList.size()>0){
			EventFieldsCondition efc = null;
			Field field = null;
			if (efcdList.size()==1){
				field = efcdList.get(0).getField();
				efc =  efcdList.get(0).getEfc();
				fieldsPart = field.getFieldName();
				conditionPart = fieldsPart+ efc.getCondition()+efc.getValue();
			}else{
				
			}
		}
		//3.根据1、2步的得到组合生成查询条件
		String sql = "select "+fieldsPart+" from "+ued.getTable().getTableName()+" where "+ conditionPart+" "+timeStampPart;

		return sql;
	}

}
